<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>10.16</title>

    <style>
      * {
        margin: 0;
        padding: 0;
      }
      body {
        width: 100%;
        height: 100%;
      }
      button {
        width: 100px;
        height: 100px;
      }
      table {
        border: 1px solid black;
      }
      th,
      td {
        border: 1px solid black;
        padding: 8px;
        text-align: left;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>
    <button>渲染</button>
    <script>
      let data = [
        {
          id: 1,
          name: "iPhone 15",
          price: 5999,
        },
        {
          id: 2,
          name: "iPhone 15 Pro",
          price: 7999,
        },
        {
          id: 3,
          name: "iPhone 15 Pro Max",
          price: 8999,
        },
      ];
      let btn = document.querySelector("button");
      let div1 = document.querySelector(".box");
      let table = document.createElement("table");
      div1.appendChild(table);
      btn.onclick = function () {
        for (let i = 0; i < data.length + 1; i++) {
          let newTr = document.createElement("tr");
          let th = document.createElement("th");
          table.appendChild(newTr);
          let Th = document.querySelector("th");
          for (let j = 0; j < data.length; j++) {
            let newTh = document.createElement("th");
            newTr.appendChild(newTh);
          }
        }
        let Th = document.querySelectorAll("th");
        Th[0].appendChild(document.createTextNode("名称"));
        Th[1].appendChild(document.createTextNode("型号"));
        Th[2].appendChild(document.createTextNode("价格"));
        console.log(Th);

        for (let i = 0; i < data.length; i++) {
          const index = i * 3;
          Th[index + 3].appendChild(document.createTextNode(data[i].id));
          Th[index + 4].appendChild(document.createTextNode(data[i].name));
          Th[index + 5].appendChild(document.createTextNode(data[i].price));
        }
      };
    </script>
  </body>
</html>
